<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <template #header>
          <span>{{ questionForm.id ? '试题修改' : '试题录入' }}</span>
        </template>
        <el-form
          ref="questionForm"
          :model="questionForm"
          label-width="120px"
          style="width: 45%"
          :rules="questionRules"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="questionForm.subjectID"
              placeholder="请选择学科"
              clearable
              filterable
              @change="changeSubjectId"
              style="width: 100%"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="questionForm.catalogID"
              placeholder="请选择目录"
              style="width: 100%"
              clearable
              filterable
            >
              <el-option
                v-for="item in dirctoryList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="questionForm.enterpriseID"
              placeholder="请选择企业"
              style="width: 100%"
              clearable
              filterable
            >
              <el-option
                v-for="item in companysList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" required>
            <el-col :span="12">
              <el-form-item prop="province">
                <el-select
                  v-model="questionForm.province"
                  placeholder="请选择市区"
                  clearable
                  filterable
                  @change="changeProvice"
                >
                  <el-option
                    v-for="item in provincesList"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="city">
                <el-select
                  v-model="questionForm.city"
                  placeholder="请选择区县"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in cityList"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="questionForm.direction"
              clearable
              filterable
              placeholder="请选择方向"
              style="width: 100%"
            >
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group
              v-model="questionForm.questionType"
              @change="clearSelectStatus"
            >
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                :label="String(item.value)"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="questionForm.difficulty">
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="String(item.value)"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <question-quill
              :content="questionForm.question"
              @checkContent="checkQuestion"
            ></question-quill>
          </el-form-item>
          <el-form-item
            label="选项:"
            v-show="questionForm.questionType !== '3'"
          >
            <questions-options
              v-for="item in questionForm.options"
              :key="item.id"
              :item="item"
              :type="questionForm.questionType"
              @getImg="getImg"
              @getChecked="getChecked"
            >
            </questions-options>
            <el-button
              type="danger"
              size="small"
              :disabled="questionForm.questionType === '1'"
              @click="addOPtion"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item label="解析视频:">
            <el-input v-model="questionForm.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <question-quill
              :content="questionForm.answer"
              @checkContent="chenckAnswer"
            ></question-quill>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input
              v-model="questionForm.remarks"
              type="textarea"
              placeholder="请输入题目备注"
            ></el-input>
          </el-form-item>
          <el-form-item label="试题标签:">
            <el-select
              v-model="questionForm.tags"
              multiple
              placeholder="请选择试题标签"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submit" v-if="questionForm.id"
              >确认修改</el-button
            >
            <el-button type="primary" @click="submit" v-else
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import QuestionQuill from '../components/question-quill.vue'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as directorys } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
import { simple as tags } from '@/api/hmmm/tags.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

import QuestionsOptions from '../components/questions-options.vue'

export default {
  name: 'question-new',
  components: {
    QuestionsOptions,
    QuestionQuill
  },
  data () {
    return {
      questionForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '', // 题干
        options: [],
        answer: '', // 答案解析
        videoURL: '',
        remarks: '',
        tags: []
      },
      subjectList: [],
      dirctoryList: [],
      companysList: [],
      provincesList: provinces(),
      cityList: [],
      direction, // 方向
      questionType, // 题型 1单选  2多选  3简答
      difficulty, // 难度  1简单  2一般  3困难
      tags: [],
      type: '', // 传给option子组件区分是单选还是多选
      allEn: [], // 所有的英文字母
      defaultEn: [], // 默认显示的四个英文字母
      questionRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择区县', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干内容', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 获取学科列表
    async getSubjectList () {
      const { data: res } = await simple()
      console.log(res)
      this.subjectList = res
    },
    // 选中的选项发生了变化 执行的内容
    changeSubjectId () {
      this.questionForm.catalogID = ''
      this.questionForm.tags = ''
    },

    changeProvice () {
      this.questionForm.city = ''
    },

    // 获取目录列表
    async getDirctoryList (subjectID) {
      const { data: res } = await directorys({ subjectID })
      console.log('directorys', res)
      this.dirctoryList = res
    },

    // 获取企业列表
    async getCompanyList () {
      const { data: res } = await list({ pagesize: '10000' })
      console.log('companys', res)
      this.companysList = res.items
    },

    // 校验题干
    checkQuestion (value) {
      this.questionForm.question = value.html
      this.$refs.questionForm.validateField('question')
    },

    // 校验答案
    chenckAnswer (value) {
      this.questionForm.answer = value.html
      this.$refs.questionForm.validateField('answer')
    },

    // 处理option中的数据
    handleOption (n) {
      for (let i = 0; i < n; i++) {
        const item = {}
        if (n === 4) {
          item.code = this.defaultEn[i]
        } else if (n === 1) {
          item.code = this.defaultEn[this.defaultEn.length - 1]
        }
        item.title = ''
        item.img = ''
        item.isRight = 0
        this.questionForm.options.push(item)
      }
    },

    getImg (url, code) {
      console.log('url', url)
      console.log('code', code)
      this.questionForm.options.forEach(item => {
        if (item.code === code) {
          item.img = url
        }
      })
    },

    getChecked (checked, code) {
      this.questionForm.options.forEach(item => {
        if (item.code === code) {
          if (checked) {
            item.isRight = 1
          } else {
            item.isRight = 0
          }
        }
      })
    },

    addOPtion () {
      this.defaultEn.push(this.allEn[this.defaultEn.length])
      console.log(this.defaultEn)
      this.handleOption(1)
    },

    // 切换单选多选时 需要将 option 选中的状态清空
    clearSelectStatus () {
      this.questionForm.options.forEach(item => {
        console.log('item', item)
        item.isRight = 0
      })
    },

    // 获取试题标签
    async gettagsList () {
      const { data: res } = await tags()
      console.log('tags', res)
      this.tags = res
    },

    // 新增试题
    submit () {
      this.$refs.questionForm.validate(async valid => {
        if (!valid) return
        // 由于接口中需要的tags字段是字符串 页面上el-select得到的是一个数组  所以需要处理
        if (this.questionForm.tags) {
          if (this.questionForm.tags.length) {
            this.questionForm.tags = this.questionForm.tags.join()
          }
        }

        if (this.questionForm.id) {
          // 修改
          await update(this.questionForm)
        } else {
          // 新增
          await add(this.questionForm)
        }
        this.$message.success(
          this.questionForm.id ? '修改试题成功' : '新增试题成功'
        )
        this.$router.push('/questions/list')
      })
    },

    // 获取试题详情
    async getQuestionDetail (id) {
      const { data: res } = await detail({ id })
      console.log('res111', res)
      this.questionForm = res
      // 当tags标签有值时 才将字符串转成数组
      if (res.tags) {
        this.questionForm.tags = res.tags.split(',')
      }
    }
  },

  created () {
    console.log(this.$route.query.id)
    if (this.$route.query.id) {
      console.log('1111111111111')
      this.getQuestionDetail(this.$route.query.id)
    }
    this.getSubjectList()
    this.getCompanyList()
    // 26个英文字母
    for (let i = 0; i < 26; i++) {
      this.allEn.push(String.fromCharCode(65 + i))
    }

    for (let i = 0; i < 4; i++) {
      this.defaultEn.push(String.fromCharCode(65 + i))
    }
    // 处理option的数据
    this.handleOption(4)
  },
  watch: {
    // 监听的字段的值 发生了变化执行的
    'questionForm.subjectID' (newVal) {
      this.getDirctoryList(newVal)
      this.gettagsList(newVal)
    },
    'questionForm.province' (newVal) {
      console.log(newVal)
      this.cityList = citys(newVal)
    }
  }
}
</script>

<style scoped>
::v-deep .ql-editor {
  min-height: 249px;
}
</style>
